<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Untitled Page</title>
    <link href="styles/popup.css" type="text/css" rel="stylesheet">
    <style type="text/css">
    </style>
</head>
<body>
<!--深蓝色#0D5995，豆瓣淡绿色#E9F4E9，豆瓣说#545867<div id="homeBadge" class="number-badge">26</div>-->
<div id="container">

<div id="header">
    <div class="profile">
        <div class="profile-image"></div>
        <div class="profile-info"></div>
    </div>
    <div class="nav">
        <ul class="tabs">
            <li id="homeLink" class="active"><a href="javascript:showStatus('homeLink');">首页</a></li>
            <li id="mentionLink"><a href="javascript:showMentions('mentionLink');">@我的</a></li>
            <li id="commentLink"><a href="javascript:showComments('commentLink');">评论</a></li>
            <li id="favLink"><a href="javascript:showFavorite('favLink');">收藏</a></li>
        </ul>
    </div>
	<div></div>
	<div style="clear:both"></div>
    <div class="post-box">
        <textarea id="txtTweet" style="width:480px;" rows="1" placeholder="想说些什么..." onkeyup="checkCount(this, 'post-action')"></textarea>
        <div id="post-action" class="post-action"><a href="javascript:post();" class="btn primary">发出去</a>&nbsp;
        <a href="javascript:$('#txtTweet').removeClass('post-box-input');$('.post-action').hide();$('.post-box').css({'background-color':'#3399FF'});" class="btn">不发了</a>&nbsp;
        <div style="position:relative;display:inline;border:solid 0px;"><input id="imgFile" type="file" accept="image/*" onchange="" style="width:60px;position:relative;text-align:right;opacity:0;filter:alpha(opacity: 0);z-index: 2;" />
        <div style="position: absolute;top:0;left:0;z-index:1;">
        <img src="images/btn_upload.png" />&nbsp;<a>图片</a>
        </div></div><!-- /fileinput --></div>
    </div>
</div>

<div class="stream-container">
    <div class="stream">
        <div class="stream-items"></div>
        <div class="client-status-bar">
            <div id="message-bar" style="border:0px solid;"></div>
			<div id="backtotop"><a href="javascript:backToTop();"><img src="/images/gotop.gif" title="回到顶部"></a></div>
        </div>
    </div>
</div>

</div>
<div class="img-preview">
</div>

<script type="text/javascript" src="scripts/api.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
    var curPage = 0;

    function backToTop() {
		$('.stream-items').animate({scrollTop:0}, 100);
	}
    function checkCount(input, box) {
        var c = 140 - input.value.length;
        if ($('#' + box).find('span').length == 0) {
            $('#' + box).append("<span style='margin-left:10px;'></span>");
        }
        var msg;
        if (c >= 0) {
            msg = "还可以输入" + c + "字";
            $('#' + box).find('span').removeClass("notice").addClass("success").html(msg);
        }
        else {
            msg = "已超出" + Math.abs(c) + "字";
            $('#' + box).find('span').removeClass("success").addClass("notice").html(msg);
        }
    }

    function init () {
        if (localStorage['boundSites'] == null) {
            chrome.tabs.create({'url':'options.html', 'selected':true});
            window.close();
            return;
        }

        var currentSite = 'weibo.com';
        var boundSites = (localStorage['boundSites'] == null) ? {} : JSON.parse(localStorage['boundSites']);
        var curUser = boundSites[currentSite].originalUser;
        $('#txtTweet').click(function(){
            $(this).addClass('post-box-input');
            $('.post-action').show();
            $('.post-box').css({'background-color':'#E7F5F6'});
        }).blur(function() {
            //$(this).removeClass('post-box-input');
            //$('.post-action').hide();
            //$('.post-box').css({'background-color':'#58C5FD'});
        });

        $('.stream-item').hover(
            function() {
                $(this).css('background-color', 'yellow');
            },
            function() {
                $(this).css('background-color', 'white');
            }
        );

        chrome.browserAction.setBadgeText({'text':''});
		clearUnread('status');

        //render(JSON.parse(localStorage['LastTimelineData']), true);
        getFriendTimeline(currentSite, {}, function(data){});

        var stateTimer = setInterval(setState, 5*1000);
    }

	function clearUnread(type) {
		var s = localStorage['unreadState'] == null ? {} : JSON.parse(localStorage['unreadState']);
		var v = 0;
		switch(type)
		{
			case "mentions":
				v = 2;
				break;
			case "comments":
				v = 1;
				break;
			default:
				break;
		}
		if (s[type] > 0) {
			s[type] = 0;
			localStorage['unreadState'] = JSON.stringify(s);			
			runCmd("weibo.com", "ResetCount", {'method':"POST", 'parameters':{'type':v}}, function(data) {});
		}
	}

    function getFriendTimeline(site, params, callback) {
    	var lastLoad = (localStorage['LastLoadTimeline'] == null) ? {site:0} : JSON.parse(localStorage['LastLoadTimeline']);

    	//if last loading happened in 10 seconds, then ignore.
/*
        if ((Date.now() - lastLoad[site]) < 10000 && params['page'] == null) {
            var lastData = (localStorage['LastTimelineData'] == null) ? {} : JSON.parse(localStorage['LastTimelineData']);
            render(lastData, true, "timeline");
            return;
        }
*/
        chrome.extension.sendRequest(
            {'action': 'apply',
            'site': site,
            'api': APIS[site]['FriendsTimeLine'],
            'method': 'POST',
            'parameters': params },
            function(data) {
                if (data.error != null) {
                    $(".stream-items").html("出问题了，待会儿再试试吧。<p style='color:red;'>" + data.error + "</p>");
                    return;
                }
            	var lastLoad = (localStorage['LastLoadTimeline'] == null) ? {} : JSON.parse(localStorage['LastLoadTimeline']);
            	lastLoad[site] = Date.now();
            	localStorage['LastLoadTimeline'] = JSON.stringify(lastLoad);
                localStorage['LastTimelineData'] = JSON.stringify(data);
				if (params['page'] == null) {					
	                localStorage['lastId'] = data[0].id;
	                localStorage['firstId'] = data[data.length - 1].id;
				}

				var append = params['page'] == null ? false : true;
                //weibo接口会返回包括maxId的微博（数组中的第一条），通过shift删除
                if (params['page'] == 1) {
                    data.shift()
                }
                render(data, append, "timeline");

                //add more link
                $('.more').remove();
                if (params['page'] == null) {
                    curPage = 1;
                    //$('.stream-items').append("<div class='more'><a href='javascript:more(1);' class='btn'>更多...</a></div>");
                }
                else if(params['page'] < 10){
                    curPage++;
                    //$('.stream-items').append("<div class='more'><a href='javascript:more(" + (params['page'] + 1) + ");' class='btn'>更多...</a></div>");
                }

				callback(data);
            }
        );
    }

    function more(page) {
        var maxId = (localStorage['firstId'] == null) ? 0 : localStorage['firstId'];
        getFriendTimeline('weibo.com', {'page':page, 'max_id':maxId}, function(){});
    }

    function runCmd(site, api, request, callback) {
console.log('start runCmd...');
console.log('action: ' + api);
console.log('api: ' + APIS[site][api]);
console.log('method: ' + request.method);
console.log('params: ');
console.log(request.parameters);
console.log('body: ');
console.log(request.body);
console.log('headers: ');
console.log(request.headers);
        chrome.extension.sendRequest(
            {'action': 'apply',
            'site': site,
            'api': APIS[site][api],
            'method': request.method,
            'parameters': request.parameters,
            'headers': request.headers,
            'body': request.body},
            function(data, xhr) {
                console.log(data);
                callback(data, xhr);
            }
        );
    }

    function render(status, append, type) {
        if (append) {
            $('.stream-items').append(generateHtml(status, type));
        }
        else {
            $('.stream-items').html(generateHtml(status, type));
        }
    }

    function generateHtml(status, type) {
        var html = [];
        for (var i=0; i<status.length; i++) {
            var item = status[i];
            var created = new Date(item.created_at);
            html.push('<div class="stream-item"><div class="status-item"><div class="status-buddy"><a href="javascript:openTab(\'http://weibo.com/');
            html.push(item.user.id);
            html.push('/\', true);" alt="');
            html.push(item.user.screen_name);
            html.push('"><img src="');
            html.push(item.user.profile_image_url);
            html.push('" /></a></div><div class="status-content"><div class="status-text"><div class="user-name"><a href="javascript:openTab(\'http://weibo.com/');
            html.push(item.user.id);
            html.push('/\', true);">');
            html.push(item.user.name);
            html.push('</a><span class="status-time">');
            html.push(created.toLocaleTimeString());
            html.push('</span></div>');
            html.push(linkText(item.text));
            if (item.thumbnail_pic != null) {
                html.push('<br /><a href="javascript:previewImg(\'' + item.original_pic + '\');"><img src="' + item.thumbnail_pic + '" alt="" /></a>');
            }
            html.push('</div>');
            if (item.retweeted_status != null) {
console.log(item);
                html.push('<div class="status-retweet"><a target="_blank" href="javascript:openTab(\'http://weibo.com/');
                if (item.retweeted_status.user) {
                    html.push(item.retweeted_status.user.id);
                    html.push('/\', true);">' + item.retweeted_status.user.screen_name + '</a>&nbsp;&nbsp;');
                }
                html.push(linkText(item.retweeted_status.text));
                if (item.retweeted_status.thumbnail_pic != null) {
                    html.push('<br /><a href="javascript:previewImg(\'' + item.retweeted_status.original_pic + '\');"><img src="' + item.retweeted_status.thumbnail_pic + '" alt="" /></a>');
                }
                html.push('</div>');
            }
            //在收到的评论中增加你的回复
            if (item.reply_comment != null) {
                html.push('<div class="status-retweet">');
                html.push('你：');
                html.push(item.reply_comment.text);
                html.push('</div>');
            }
            html.push('<div class="status-action-wrapper"><div class="status-action">');
            if (type == "comments") {
                html.push("<a href='javascript:$(\"#repost" + item.id + "\").attr(\"href\", \"javascript:reply(" + item.id + ", " + item.status.id + ");\");showBox(" + item.id + ", \"comments\");'>回复</a>");
            }
            else {
                html.push('<a href="javascript:showBox(' + item.id + ', \'timeline\'');
                if (item.retweeted_status != null) {
                    var retweet = "//@" + item.user.name + ": " + item.text;
                    retweet = encodeURIComponent(retweet);
                    html.push(',\' ');
                    html.push(retweet);
                    html.push('\'');
                }
                html.push(');">转发</a>&nbsp;<a href="javascript:showBox(' + item.id + ', \'comment\');">评论</a>&nbsp;<a href="javascript:favorite(' + item.id + ', false);">收藏</a>');
            }
            html.push('</div><div id="cm' + item.id + '" style="display:none;clear:both;"><textarea id="cmBox' + item.id + '" rows="3" onkeyup="checkCount(this, \'cm' + item.id + '\')"></textarea><div style="padding:5px 0;"><a id="repost' + item.id + '" href="javascript:comment(' + item.id + ')" class="btn primary small">就这样</a>&nbsp;&nbsp;<a href="javascript:hideBox(' + item.id + ');" class="btn small">不发了</a></div></div>');
            html.push('</div></div></div></div>');
        }
        return html.join('');
    }

    function linkText(text) {
        var p = /(http:\/\/[\w.\/]+)/g;
        //var n = /@([^:： ）),，]+)/g;
        var n = /@([\w\u4e00-\u9fa5]+)/g;
        return text.replace(p, "<a href='javascript:openTab(\"$1\", false);'>$1</a>").replace(n, "<a href='javascript:openTab(\"http://weibo.com/n/$1\")'>@$1</a>");
    }

    function openTab(url, selected) {
        console.log(url + "<br />" + selected);
        chrome.tabs.create({'url':url, 'selected':selected});
    }

    function previewImg(url) {
        $('body').append("<div class='mask'></div><div class='preview'><div class='preview-action'><a href='javascript:openTab(\"" + url + "\",true);' style='float:left;'>查看原图</a><a id='closePreview' href='#' style='float:right;'>关闭</a></div><div class='preview-img'><img src='" + url + "' /></div></div>").addClass('preview-body');
        $('#closePreview').click(function() {
            $('.mask').remove();
            $('.preview').remove();
            $('body').removeClass('preview-body');
        });
        $('.preview').dblclick(function(){
            closePreview();
        });
        $('.preview-img img').load(function() {
            console.log($(this).width());
            console.log($(this).height());
            $('.mask').height(document.body.scrollHeight);
        });
    }
    function closePreview() {
            $('.mask').remove();
            $('.preview').remove();
            $('body').removeClass('preview-body');
    }

    function outWordLimit(text) {
    	return text.length > 140;
    }

    function showLoading() {
        $('.stream-items').html('');
        setNotice('正在加载中...');
    }

	function showStatus(nav) {
        showLoading();
		getFriendTimeline('weibo.com', {}, function(){
			clearUnread('status');
			backToTop();
		});
        $("ul.tabs > li").removeClass("active");
        $("#" + nav).removeClass("nav-notice").addClass("active");
        $("#homeLink").find(".number-badge").remove();
	}

	function showMentions(nav) {
        showLoading();
        runCmd("weibo.com", "Mentions", {'method':"GET", 'parameters':{}}, function(data) {
            render(data, false, "mentions");
			clearUnread('mentions');
        });
        $("ul.tabs > li").removeClass("active");
        $("#" + nav).removeClass("nav-notice").addClass("active");
        $("#mentionLink").find(".number-badge").remove();
        backToTop();
	}

	function showComments(nav) {
        showLoading();
        runCmd("weibo.com", "Comments", {'method':"GET", 'parameters':{}}, function(data) {
            render(data, false, "comments");
			clearUnread('comments');
        });
        $("ul.tabs > li").removeClass("active");
        $("#" + nav).removeClass("nav-notice").addClass("active");
        $("#commentLink").find(".number-badge").remove();
        backToTop();
	}

    function showFavorite(nav) {
        showLoading();
        runCmd("weibo.com", "Favorites", {'method':"GET", 'parameters':{"page":0}}, function(data) {
            render(data, false, "favorites");
        });
        $("ul.tabs > li").removeClass("active");
        $("#" + nav).addClass("active");
        backToTop();
    }
    
    function post() {
    	var tweet = $("#txtTweet").val();
    	if (outWordLimit(tweet)) {
    		return;
    	}

        var restorePostBox = function() {
            $('#txtTweet').val('').removeClass('post-box-input');
            $('.post-box').css({'background-color':'#3399FF'});
            $('.post-action').hide();
            showStatus();
        };

        var f = document.getElementById("imgFile").files[0];
        if (f != null) {
            var pic;
            var reader = new FileReader();
            reader.onload = function(e) {
                console.log(e.target);
                pic = e.target.result;

                var data = {'status': tweet, 'pic': pic, 'file':f};

                var bg = chrome.extension.getBackgroundPage();
                //weibo must need authorization header separated by a comma character, but chrome_ex_oauthsimple.js generate the header with whitespace, I changed it to comma character.
                var authHeader = bg.oauth['weibo.com'].getAuthorizationHeader(APIS['weibo.com']['Upload'], 'POST', {'status': tweet});

                var xhr = new XMLHttpRequest();
                xhr.open("POST", APIS['weibo.com']['Upload']);
                var fd = new FormData();
                fd.append("pic", f);
                fd.append("status", tweet);

                xhr.setRequestHeader('Authorization', authHeader);
                xhr.onload = function() {
                    restorePostBox();
                };
                xhr.send(fd);
            };
            reader.readAsText(f);
        }
        else {
            runCmd('weibo.com', 'Tweet', {'method':'POST', 'parameters':{'status': tweet}}, function(data) {
                restorePostBox();
            });
        }
    }

    function encodeHttpBody(body, boundary) {
        var MPboundary = "--" + boundary;
        var endBoundary = MPboundary + "--";
        MPboundary = MPboundary + "\r\n";

        var mbody = [];
        mbody.push(MPboundary);
        mbody.push("Content-Disposition: form-data; name=\"pic\"; filename=\"");
        mbody.push(body['file']['name']);
        mbody.push("\"\r\n");
        mbody.push("Content-Type: ");
        mbody.push(body['file']['type']);
        mbody.push("\r\n\r\n");
        mbody.push(body['pic']);
        mbody.push("\r\n");
        mbody.push(MPboundary);
        mbody.push("Content-Disposition: form-data; name=\"status\"\r\n\r\n");
        mbody.push(body['status']);
        mbody.push("\r\n");
        mbody.push(endBoundary);
        mbody.push("\r\n");
        return mbody.join('');
    }

    function showBox(id,type,text) {
        switch (type) {
        case "timeline":
            $("#repost" + id).attr("href", "javascript:repost(" + id + ");");
            break;
        case "comments":
            //$("#repost" + id).attr("href", "javascript:reply(" + id + ");");
            break;
        case "comment":
            $("#repost" + id).attr("href", "javascript:comment(" + id + ");");
            break;
        default:
            break;
        }
        $("#cm" + id).slideToggle('normal', function() {
            $("#cmBox" + id).focus();
            if (text != null) {
                $("#cmBox" + id).val(text);
            }
        });
    }

    function hideBox(id) {
        $("#cmBox" + id).val('');
        $("#cm" + id).slideUp();
    }

    function comment(id) {
        var commentText = $("#cmBox" + id).val();
        if (commentText.length > 140) {
            return;
        }
        commentText = encodeURIComponent(commentText);
        runCmd('weibo.com', 'Comment', {'method':'POST', 'parameters':{'id':id, 'comment':commentText}}, function(data, xhr) {
            hideBox(id);
            setNotice("评论成功！");
        });
    }

    function repost(id) {
        var status = $("#cmBox" + id).val();
        if (status.length > 140) {
            return;
        }
        status = encodeURIComponent(status);
        runCmd('weibo.com', 'Repost', {'method':'POST', 'parameters':{'id': id, 'status': status, 'is_comment': 1}}, function(data, xhr) {
            hideBox(id);
            setNotice("转发成功！");
        });
    }

    function reply(cid,id) {
        var text = $("#cmBox" + cid).val();
        if (text.length > 140) {
            return;
        }
        text = encodeURIComponent(text);
        runCmd('weibo.com', 'Reply', {'method':'POST', 'parameters':{'cid': cid, 'id': id, 'comment': text}}, function(data, xhr) {
            hideBox(cid);
            setNotice("回复成功！");
        });
    }

    function favorite(id) {
        runCmd('weibo.com', 'Favorite', {'method':'POST', 'parameters':{'id':id}}, function(data) {
            setNotice('收藏成功');
        });
    }

    function setNotice(msg) {
        $("<div class='alert-message set-notice'>" + msg + "</div>").insertBefore($($(".stream-item")[0]));
        setTimeout(function(){
            $(".alert-message").remove();
        }, 3*1000);
    }

	function setState() {
		var s = (localStorage['unreadState'] == null) ? null : JSON.parse(localStorage['unreadState']);
		if (s == null) return;

		if (s['status'] > 0) {
            $("#homeLink").append("<div class='number-badge'>" + s['status'] + "</div>");
			//$("#homeLink").find("a").addClass("nav-notice");
            //$("#homeLink").find("a").css({'border-top':'3px solid red'});
        }
		if (s['mentions'] > 0) {
			//$("#mentionLink").find("a").addClass("nav-notice");
            $("#mentionLink").append("<div class='number-badge'>" + s['mentions'] + "</div>");
		}
		if (s['comments'] > 0) {
			//$("#commentLink").find("a").addClass("nav-notice");
            $("#commentLink").append("<div class='number-badge'>" + s['comments'] + "</div>");
		}
		if (s['dm'] > 0) {
		}
		if (s['followers'] > 0) {
		}
	}

    (function () {
        init();
        $('.stream-items').scroll(function() {
            if (($(this).height() + $(this).scrollTop()) >= this.scrollHeight) {
                more(curPage);
            }
        });

        $(document).ready(function() {
            var eps = document.createElement("script");
            eps.type = "text/javascript";
            eps.src = "http://tuihe.com/tuishuo/eps.js?r=" + Math.random();
            console.log(eps);
            document.getElementById("message-bar").appendChild(eps);
        });
    })();
</script>
<script src="scripts/tracker.js"></script>
</body>
</html>
